package com.tinghua.repositories;

import com.tinghua.pojo.Customer;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
    //参数方式一
    @Query("from Customer where custName=?1 ")
    List<Customer> findCustomerByName(String name);
    //参数方式二
    @Query("from Customer where custName=:name ")
    List<Customer> findCustomerByName2(@Param("name") String name);
    //修改
    @Transactional //通常放在业务逻辑上，这里没有业务逻辑就直接放到操作方法上了
    @Modifying  //增删改都需要这个注解，并且放到对应的执行方法上，也就是此处
    @Query("update Customer c set c.custAddress=:address where c.custId = :id")
    int updateCustomer(@Param("address") String address, @Param("id") Long id);
    //删除
    @Transactional
    @Modifying
    @Query("delete from Customer c where c.custId = :id")
    int deleteCustomer(@Param("id") Long id);
    //新增：jpa不支持新增数据，但在下是可以伪插入的
//    @Transactional
//    @Modifying
//    @Query("INSERT into Customer (customer) select c.custName from Customer c where c.custId")
//    int insertCustomerBySelect(Long id);

    //使用原生sql
    @Query(value = "select * from cst_customer where cust_name = :name", nativeQuery = true)
    List<Customer> selectAllByName(@Param("name") String name);
}
